<?php


namespace app\admin\controller;


use app\common\model\AdminLogModel;
use app\common\model\UserModel;
use think\facade\Request;

class AdminlogController extends BaseController
{

    public function index()
    {
        return $this->fetch();
    }

    /**
     * 日志列表
     * @return \think\response\Json
     */
    public function getList()
    {
        $adminid    = Request::param("adminid");
        $title      = Request::param("title");
        $uid        = Request::param("uid");
        $nick_name  = Request::param("nick_name");
        $start_time = Request::param("start_time");
        $end_time   = Request::param("end_time");
        // 分页
        $page  = Request::param("page");
        $limit = Request::param("limit");
        // 排序
        $sort_field = Request::param("field", '', 'trim');
        $sort_order = Request::param("order", '', 'trim');

        $order = "id desc";
        if (!empty($sort_field) && !empty($sort_order)) {
            $order = sprintf("%s %s", $sort_field, $sort_order);
        }

        $where    = [];
        $where_or = [];
        if ($adminid) {
            $where[]    = ['adminid', '=', is_numeric($adminid) ? $adminid : '-1'];
            $where_or[] = ['mgrid', '=', is_numeric($adminid) ? $adminid : '-1'];
        }
        if ($uid) {
            $where[] = ['uid', '=', is_numeric($uid) ? $uid : '-1'];
        }
        if (mb_strlen($nick_name, 'UTF-8') > 0) {
            // 查询用户昵称
            $user_ids = UserModel::whereLike('nick_name', "%$nick_name%")->column('id');
            $user_ids = $user_ids ?: [-1];
            $where[]  = ['uid', 'in', $user_ids];
        }

        if ($title) {
            $where[] = ['content', 'like', "%{$title}%"];
        }
        if ($start_time) {
            $where[] = ['create_time', '>=', $start_time];
        }
        if ($end_time) {
            $where[] = ['create_time', '<=', $end_time];
        }

        $count = AdminLogModel::where($where)->whereOr($where_or)->count("id");

        if ($count > 0) {
            $notice = AdminLogModel::with([
                'admin'   => function ($query) {
                    $query->field('id,name');
                },
                'user'    => function ($query) {
                    $query->field('id,nick_name');
                },
                'mgruser' => function ($query) {
                    $query->field('id,nick_name');
                },
            ])->where($where)
                ->whereOr($where_or)
                ->order($order)
                ->page($page, $limit)
                ->select();

            return json(["code" => 0, "msg" => "", "data" => $notice, "count" => $count]);
        }

        return self::bulidFail('暂无数据');
    }
}